import torch
import torchvision
from PIL import Image
from torch import nn

img_type = ["airplane","automobile","bird","cat","deer","dog","frog","horse","ship","truck"]

class MyMod(nn.Module):
    def __init__(self):
        super(MyMod, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(in_features=1024, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

    def forward(self, x):
        output = self.model(x)
        return output


def classifier(image_path):
    model = torch.load("mymod.pth", map_location=torch.device('cpu'))
    print(model)

    image = Image.open(image_path)
    print(image)
    image = image.convert('RGB')
    transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)),
                                                torchvision.transforms.ToTensor()])

    image = transform(image)
    print(image.shape)
    image = torch.reshape(image, (1, 3, 32, 32))
    model.eval()
    with torch.no_grad():
        output = model(image)
    print(output)
    print("分类：")
    print()
    print(img_type[output.argmax(1).item()])


if __name__ == "__main__":
    image_path = "../data/deer.png"
    classifier(image_path)